package ink.metoo.auto.fishpi.chatroom.handler

import ink.metoo.auto.fishpi.chatroom.ChatRooms
import ink.metoo.auto.fishpi.chatroom.Message

class OnlineTypeHandler : TypeHandler {

    override val type: Message.Type = Message.Type.ONLINE

    override fun handle(text: String, message: Message) {
        val newOnlineUsers = message.users
            .mapNotNull { user -> user.userName }
            .toSet()
        val oldOnlineUsers = ChatRooms.onlineUsers

        val map = mutableMapOf<String, Int>()

        newOnlineUsers.forEach {
            map[it] = 1
        }

        oldOnlineUsers.forEach {
            map.merge(it, 2) { old, new -> old + new }
        }

        val joinUsers = mutableSetOf<String>()
        val leaveUsers = mutableSetOf<String>()

        map.forEach { (userName, count) ->
            when (count) {
                1 -> joinUsers.add(userName)
                2 -> leaveUsers.add(userName)
            }
        }
        val hasJoin = joinUsers.isNotEmpty()
        val hasLeave = leaveUsers.isNotEmpty()
        if (hasJoin || hasLeave) {
            var content = ""
            if (hasJoin) {
                content += " [+] ${joinUsers.joinToString(", ")}"
            }
            if (hasLeave) {
                content += " [-] ${leaveUsers.joinToString(", ")}"
            }
            ChatRooms.systemConsole(message, "用户$content")
        }
        ChatRooms.onlineUsers = newOnlineUsers
        if (ChatRooms.discussing != message.discussing) {
            ChatRooms.discussing = message.discussing
            ChatRooms.systemConsole(message, "当前话题: ${message.discussing}")
        }
    }
}